package com.skt.controller;

import com.skt.domain.DTO.UserQueryDTO;
import com.skt.domain.DTO.request.CreateCategoryRequest;
import com.skt.domain.DTO.request.OrderQueryRequest;
import com.skt.domain.DTO.request.RejectMerchantRequest;
import com.skt.domain.DTO.request.UpdateCategoryRequest;
import com.skt.domain.VO.AdminMerchantApprovalVO;
import com.skt.domain.VO.AdminOrderListVO;
import com.skt.domain.VO.CategoryVO;
import com.skt.domain.VO.UserVO;
import com.skt.result.PageResult;
import com.skt.service.AdminService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Max;
import javax.validation.constraints.Min;
import java.time.LocalDate;

@RestController
@RequiredArgsConstructor
@RequestMapping("/admin")
@Tag(name = "平台管理员接口")
public class AdminController {
    private final AdminService adminService;

    @Operation(
            summary = "审核通过商家注册",
            description = "管理员审核并批准一个状态为“待审核”的商家注册申请。该操作具备幂等性：对非“待审核”状态的商家重复调用不会产生副作用。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "审核成功，返回审核后的商家信息"),
            @ApiResponse(responseCode = "400", description = "商家ID无效（如非正整数）"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证或不具备管理员权限"),
            @ApiResponse(responseCode = "404", description = "商家不存在"),
            @ApiResponse(responseCode = "409", description = "商家当前状态不允许审核（例如已通过、已拒绝或已注销）")
    })
    @PutMapping("/merchants/{id}/approve")
    public ResponseEntity<AdminMerchantApprovalVO> approveMerchant(
            @Parameter(description = "商家用户ID，必须为大于0的整数", required = true, example = "2001")
            @PathVariable
            @Min(value = 1, message = "商家ID必须为正整数")
            Long id) {
        AdminMerchantApprovalVO vo = adminService.approveMerchant(id);
        return ResponseEntity.ok(vo);
    }


    @Operation(
            summary = "拒绝商家注册申请",
            description = "管理员拒绝一个状态为“待审核”的商家注册申请。操作具备幂等性：仅当商家状态为“待审核”时生效，拒绝原因可选但建议提供。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "拒绝成功，返回拒绝后的商家信息"),
            @ApiResponse(responseCode = "400", description = "商家ID无效（如非正整数）或拒绝原因格式不合法"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证或不具备管理员权限"),
            @ApiResponse(responseCode = "404", description = "商家不存在"),
            @ApiResponse(responseCode = "409", description = "商家当前状态不允许审核（例如已通过、已拒绝或已注销）")
    })
    @PutMapping("/merchants/{id}/reject")
    public ResponseEntity<AdminMerchantApprovalVO> rejectMerchant(
            @Parameter(description = "商家用户ID，必须为大于0的整数", required = true, example = "2001")
            @PathVariable
            @Min(value = 1, message = "商家ID必须为正整数")
            Long id,

            @Parameter(description = "拒绝原因（可选），建议提供以提升用户体验", example = "营业执照信息不清晰")
            @RequestBody(required = false)
            RejectMerchantRequest request) {
        // 例子 String status = age >= 18 ? "成年人" : "未成年人";
        String rejectionReason = request != null ? request.getReason() : null;
        AdminMerchantApprovalVO vo = adminService.rejectMerchant(id, rejectionReason);
        return ResponseEntity.ok(vo);
    }


    @Operation(
            summary = "查询服装分类列表",
            description = "管理员分页查询所有服装分类，支持按名称模糊搜索。返回结果包含分类基本信息及父分类名称（如适用）。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功，返回分页分类列表"),
            @ApiResponse(responseCode = "400", description = "分页参数无效（如 pageNum < 1 或 pageSize 超出范围）"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证或不具备管理员权限"),
            @ApiResponse(responseCode = "404", description = "（预留）未找到符合条件的分类（当前逻辑不会触发）")
    })
    @GetMapping("/categories")
    public ResponseEntity<PageResult<CategoryVO>> listCategories(
            @Parameter(description = "分类名称模糊查询关键词（可选）", example = "连衣裙")
            @RequestParam(required = false)
            String name,

            @Parameter(description = "页码，从1开始", example = "1")
            @RequestParam(defaultValue = "1")
            @Min(value = 1, message = "页码必须大于0")
            Integer pageNum,

            @Parameter(description = "每页数量，建议1~100", example = "10")
            @RequestParam(defaultValue = "10")
            @Min(value = 1, message = "每页数量必须大于0")
            @Max(value = 100, message = "每页数量不能超过100")
            Integer pageSize) {

        // 权限校验和业务逻辑全部交给 Service
        PageResult<CategoryVO> result = adminService.listCategories(name, pageNum, pageSize);
        return ResponseEntity.ok(result);
    }


    @Operation(
            summary = "新增服装分类",
            description = "管理员创建一个新的服装分类。可指定父分类（parentId=0 表示顶级分类），需确保同级分类名称唯一。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "201", description = "分类创建成功，返回新建分类的详细信息"),
            @ApiResponse(responseCode = "400", description = "请求参数无效（如名称为空、长度超限、父分类不存在等）"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证、非管理员或账户被禁用"),
            @ApiResponse(responseCode = "409", description = "同级分类名称重复或数据库约束冲突")
    })
    @PostMapping("/categories")
    public ResponseEntity<CategoryVO> createCategory(
            @Parameter(description = "新增分类的请求体", required = true)
            @Valid @RequestBody
            CreateCategoryRequest request) {

        // 所有校验和业务逻辑交由 Service 处理
        CategoryVO createdCategory = adminService.createCategory(request);

        return ResponseEntity.status(HttpStatus.CREATED).body(createdCategory);
    }


    @Operation(
            summary = "更新服装分类",
            description = "管理员更新指定 ID 的服装分类信息。需确保分类存在、未被删除，且更新后不违反业务规则（如名称非空、无同级重名、父子关系无循环等）。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "分类更新成功，返回更新后的分类信息"),
            @ApiResponse(responseCode = "400", description = "请求参数无效（如分类ID非正整数、名称为空、父ID非法、排序值为负等）"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证、非管理员或账户被禁用"),
            @ApiResponse(responseCode = "404", description = "分类不存在或已被逻辑删除"),
            @ApiResponse(responseCode = "409", description = "同级分类名称重复，或更新操作因并发冲突失败")
    })
    @PutMapping("/categories/{id}")
    public ResponseEntity<CategoryVO> updateCategory(
            @Parameter(description = "要更新的分类ID，必须为大于0的整数", required = true, example = "101")
            @PathVariable
            @Min(value = 1, message = "分类ID必须为正整数")
            Long id,

            @Parameter(description = "更新分类的请求体", required = true)
            @Valid @RequestBody
            UpdateCategoryRequest request) {

        CategoryVO updatedCategory = adminService.updateCategory(id, request);
        return ResponseEntity.ok(updatedCategory);
    }


    @Operation(
            summary = "删除服装分类",
            description = "管理员逻辑删除指定 ID 的服装分类。要求：分类存在且未删除、无子分类、无关联服装商品。删除成功后异步记录操作日志。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "204", description = "删除成功，无返回内容"),
            @ApiResponse(responseCode = "400", description = "分类ID无效（非正整数）"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证、非管理员或账户被禁用"),
            @ApiResponse(responseCode = "404", description = "分类不存在或已被删除"),
            @ApiResponse(responseCode = "409", description = "分类下存在子分类或关联服装商品，无法删除")
    })
    @DeleteMapping("/categories/{id}")
    public ResponseEntity<Void> deleteCategory(
            @Parameter(description = "要删除的分类ID，必须为大于0的整数", required = true, example = "101")
            @PathVariable
            @Min(value = 1, message = "分类ID必须为正整数")
            Long id) {

        adminService.deleteCategory(id);
        return ResponseEntity.noContent().build();
    }


    @Operation(
            summary = "查看平台用户列表",
            description = "管理员分页查询平台用户列表，支持多条件筛选。返回结果包含脱敏后的用户信息。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功，返回分页用户列表"),
            @ApiResponse(responseCode = "400", description = "查询参数无效（如分页参数超出范围）"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证或不具备管理员权限")
    })
    @GetMapping("/users")
    public ResponseEntity<PageResult<UserVO>> getUserList(@Valid UserQueryDTO queryDTO) {
        PageResult<UserVO> result = adminService.getUserList(queryDTO);
        return ResponseEntity.ok(result);
    }


    @Operation(
            summary = "查看平台订单总览",
            description = "管理员分页查询平台订单，支持多条件筛选。" +
                    "支持按订单状态、时间范围、订单号、收货人姓名/手机号、店铺ID、用户ID进行过滤。" +
                    "数据根据管理员等级限制可见范围（超级管理员全量，区域管理员仅限本区域）。"
    )
    @ApiResponses({
            @ApiResponse(responseCode = "200", description = "查询成功，返回分页订单列表"),
            @ApiResponse(responseCode = "400", description = "查询参数无效，如页码小于1、每页数量超出范围、时间跨度超3个月、状态值非法等"),
            @ApiResponse(responseCode = "403", description = "当前用户未认证、非管理员或账户被禁用"),
            @ApiResponse(responseCode = "404", description = "无匹配订单"),
            @ApiResponse(responseCode = "500", description = "服务器内部错误，如数据库查询超时")
    })
    @PostMapping("/orders")
    public ResponseEntity<PageResult<AdminOrderListVO>> listOrders(
            @Parameter(description = "订单查询请求体", required = true)
            @Valid @RequestBody
            OrderQueryRequest request) {

        PageResult<AdminOrderListVO> result = adminService.listOrders(request);
        return ResponseEntity.ok(result);
    }

    /**
     * http://localhost:8080/v3/api-docs
     */
}
